package org.example.order.listener;

import com.rabbitmq.client.Channel;
import org.example.order.cache.OrderCacheList;
import org.example.order.domain.Order;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * Description: 死信队列消息侦听器
 * Author: e
 * CreateDate: 2021-08-02
 */
@Component
public class CancelOrderMessageListener implements ChannelAwareMessageListener {

    @Override
    @RabbitListener(queues = "q.order.dlx", ackMode = "MANUAL")
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        String orderId = new String(body);
        Order order = OrderCacheList.findOrderByOrderId(Long.parseLong(orderId));
        if (order.getStatus() == 0) {
            //如果订单未支付，则取消订单
            OrderCacheList.updateOrderStatus(Long.parseLong(orderId), 2, "订单超时");
            System.out.println("取消订单:" + order.toString());
        }
        //消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
